<template>
  <div class="freshair-monitor">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新风设备管理</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左上：新风设备模块（控制模块 + 阈值展示） -->
        <el-col :span="12">
          <div class="device-module">
            <div class="module-header">
              <div class="header-left">
                <div class="title-decorator"></div>
                <!-- 标题与红色离线标识 -->
                <span class="module-title">新风设备</span>
                <span class="device-status offline">离线</span>
              </div>
              <!-- 右侧参数配置按钮，打开“编辑详情”弹窗 -->
              <el-button type="primary" size="small" @click="showSettings">参数配置</el-button>
            </div>

            <div class="device-content">
              <!-- 设备选择：默认“区域控制器 - 新风设备_1”，支持列表切换 -->
              <div class="device-selector">
                <el-select v-model="selectedDevice" placeholder="请选择设备" style="width: 100%">
                  <el-option
                    v-for="device in devices"
                    :key="device.id"
                    :label="formatDeviceLabel(device)"
                    :value="device.id">
                  </el-option>
                </el-select>
              </div>

              <!-- 阈值展示卡片：温度阈值、湿度阈值 -->
              <div class="threshold-cards">
                <!-- 温度阈值卡片 -->
                <div class="threshold-card temperature">
                  <div class="card-icon">
                    <!-- 温度计类图标（简化版SVG） -->
                    <svg viewBox="0 0 24 24" width="28" height="28" aria-label="thermometer">
                      <path d="M10 2a2 2 0 0 1 4 0v8.09a5 5 0 1 1-4 0V2z" fill="#409EFF" opacity="0.8"/>
                      <rect x="11" y="4" width="2" height="6" fill="#fff" opacity="0.9"/>
                    </svg>
                  </div>
                  <div class="card-values">
                    <div class="value">{{ thresholds.tempMin }} - {{ thresholds.tempMax }}<span class="unit">℃</span></div>
                    <div class="desc">温度阈值</div>
                  </div>
                </div>

                <!-- 湿度阈值卡片 -->
                <div class="threshold-card humidity">
                  <div class="card-icon">
                    <!-- 水滴图标（简化版SVG） -->
                    <svg viewBox="0 0 24 24" width="28" height="28" aria-label="humidity">
                      <path d="M12 2s6 6 6 10a6 6 0 1 1-12 0c0-4 6-10 6-10z" fill="#67C23A" opacity="0.8"/>
                    </svg>
                  </div>
                  <div class="card-values">
                    <div class="value">{{ thresholds.humMin }} - {{ thresholds.humMax }}<span class="unit">% RH</span></div>
                    <div class="desc">湿度阈值</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 右上：设备状态模块 -->
        <el-col :span="12">
          <div class="status-module">
            <div class="module-header">
              <div class="header-left">
                <div class="title-decorator"></div>
                <span class="module-title">设备状态</span>
              </div>
            </div>
            
            <div class="status-content">
              <!-- 设备状态卡片 -->
              <div class="status-cards">
                <div class="status-card">
                  <div class="status-label">设备状态</div>
                  <div class="status-value">{{ deviceStatus.power }}</div>
                </div>
                <div class="status-card">
                  <div class="status-label">风速状态</div>
                  <div class="status-value">{{ deviceStatus.fanStatus }}</div>
                </div>
                <div class="status-card">
                  <div class="status-label">风速模式</div>
                  <div class="status-value">{{ deviceStatus.fanMode }}</div>
                </div>
                <div class="status-card">
                  <div class="status-label">运行模式</div>
                  <div class="status-value">{{ deviceStatus.runMode }}</div>
                </div>
              </div>
              
              <!-- 环境数据卡片 -->
              <div class="env-cards">
                <div class="env-card">
                  <div class="env-label">PM2.5</div>
                  <div class="env-value">
                    <span class="value">{{ envData.pm25 }}</span>
                    <span class="unit">μg/m³</span>
                  </div>
                </div>
                <div class="env-card">
                  <div class="env-label">PM10</div>
                  <div class="env-value">
                    <span class="value">{{ envData.pm10 }}</span>
                    <span class="unit">μg/m³</span>
                  </div>
                </div>
                <div class="env-card">
                  <div class="env-label">CO2</div>
                  <div class="env-value">
                    <span class="value">{{ envData.co2 }}</span>
                    <span class="unit">ppm</span>
                  </div>
                </div>
                <div class="env-card">
                  <div class="env-label">TVOC</div>
                  <div class="env-value">
                    <span class="value">{{ envData.tvoc }}</span>
                    <span class="unit">ppb</span>
                  </div>
                </div>
                <div class="env-card">
                  <div class="env-label">CH2O</div>
                  <div class="env-value">
                    <span class="value">{{ envData.ch2o }}</span>
                    <span class="unit">μg/m³</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 左下：温湿度曲线模块 -->
        <el-col :span="12">
          <div class="chart-module">
            <div class="module-header">
              <div class="header-left">
                <div class="title-decorator"></div>
                <span class="module-title">温湿度曲线</span>
              </div>
            </div>
            
            <div class="chart-content">
              <div ref="tempHumChart" class="chart-container"></div>
            </div>
          </div>
        </el-col>

        <!-- 右下：运行日志模块 -->
        <el-col :span="12">
          <div class="log-module">
            <div class="module-header">
              <div class="header-left">
                <div class="title-decorator"></div>
                <span class="module-title">运行日志</span>
              </div>
            </div>
            
            <div class="log-content">
              <!-- 表格表头 -->
              <div class="log-table">
                <div class="table-header">
                  <div class="header-cell">序号</div>
                  <div class="header-cell">时间</div>
                  <div class="header-cell">日志</div>
                </div>
                
                <!-- 表格内容 -->
                <div class="table-body" v-loading="logLoading">
                  <div v-if="logs.length === 0 && !logLoading" class="no-data">
                    <div class="no-data-icon">
                      <svg viewBox="0 0 24 24" width="48" height="48">
                        <!-- 放大镜图标 -->
                        <circle cx="11" cy="11" r="8" fill="none" stroke="#409eff" stroke-width="2"/>
                        <path d="m21 21-4.35-4.35" stroke="#409eff" stroke-width="2"/>
                        <!-- 文件图标 -->
                        <rect x="6" y="4" width="8" height="10" rx="1" fill="#409eff" opacity="0.3"/>
                        <line x1="8" y1="7" x2="12" y2="7" stroke="#409eff" stroke-width="1"/>
                        <line x1="8" y1="9" x2="12" y2="9" stroke="#409eff" stroke-width="1"/>
                        <line x1="8" y1="11" x2="10" y2="11" stroke="#409eff" stroke-width="1"/>
                      </svg>
                    </div>
                    <div class="no-data-text">暂无数据</div>
                  </div>
                  
                  <div v-for="(log, index) in logs" :key="index" class="table-row">
                    <div class="table-cell">{{ index + 1 }}</div>
                    <div class="table-cell">{{ log.time }}</div>
                    <div class="table-cell">{{ log.content }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- “编辑详情”弹窗：字段与交互按需求配置 -->
    <el-dialog title="编辑详情" :visible.sync="settingsVisible" width="700px" :close-on-click-modal="false">
      <!-- 使用校验规则，保留只读字段为禁用状态；两列布局满足字段分组展示需求 -->
      <el-form ref="settingsFormRef" :model="settingsForm" :rules="settingsRules" label-width="120px">
        <!-- 两列布局：左列 / 右列 -->
        <el-row :gutter="16" class="edit-details-grid">
          <el-col :span="12">
            <!-- 左列：设备类型（只读下拉） -->
            <el-form-item label="设备类型" prop="deviceType" required>
              <el-select v-model="settingsForm.deviceType" disabled style="width:100%">
                <el-option label="新风设备" value="新风设备"></el-option>
              </el-select>
            </el-form-item>
            <!-- 左列：设备名称（可编辑） -->
            <el-form-item label="设备名称" prop="deviceName" required>
              <el-input v-model="settingsForm.deviceName" placeholder="请输入设备名称"></el-input>
            </el-form-item>
            <!-- 左列：温度阈值（区间输入） -->
          <el-form-item label="温度阈值" required>
            <div class="range-inputs">
              <!-- 紧凑单行显示：限制输入框宽度为100px，避免换行 -->
              <el-input v-model.number="settingsForm.tempRangeLow" placeholder="下限" style="width: 100px"></el-input>
              <span class="range-sep">-</span>
              <el-input v-model.number="settingsForm.tempRangeHigh" placeholder="上限" style="width: 100px"></el-input>
              <span class="range-unit">℃</span>
            </div>
          </el-form-item>
            <!-- 左列：温度系数（可编辑） -->
            <el-form-item label="温度系数">
              <el-input v-model.number="settingsForm.tempCoefficient" placeholder="请输入温度系数"></el-input>
            </el-form-item>
            <!-- 左列：关联传感器（下拉） -->
            <el-form-item label="关联传感器">
              <el-select v-model="settingsForm.sensorOption" style="width:100%">
                <el-option label="自身传感器" value="self"></el-option>
                <el-option label="外置传感器" value="external"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 右列：所属库房（只读下拉） -->
            <el-form-item label="所属库房" prop="warehouse" required>
              <el-select v-model="settingsForm.warehouse" disabled style="width:100%">
                <el-option label="A 库房" value="A 库房"></el-option>
              </el-select>
            </el-form-item>
            <!-- 右列：设备编号（只读下拉） -->
            <el-form-item label="设备编号" prop="deviceNumber" required>
              <el-select v-model="settingsForm.deviceNumber" disabled style="width:100%">
                <el-option label="01" value="01"></el-option>
              </el-select>
            </el-form-item>
            <!-- 右列：湿度阈值（区间输入） -->
          <el-form-item label="湿度阈值" required>
            <div class="range-inputs">
              <!-- 紧凑单行显示：限制输入框宽度为100px，避免换行 -->
              <el-input v-model.number="settingsForm.humRangeLow" placeholder="下限" style="width: 100px"></el-input>
              <span class="range-sep">-</span>
              <el-input v-model.number="settingsForm.humRangeHigh" placeholder="上限" style="width: 100px"></el-input>
              <span class="range-unit">% RH</span>
            </div>
          </el-form-item>
            <!-- 右列：湿度系数（可编辑） -->
            <el-form-item label="湿度系数">
              <el-input v-model.number="settingsForm.humCoefficient" placeholder="请输入湿度系数"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 修改方式（整行显示） -->
        <el-form-item label="修改方式">
          <el-radio-group v-model="settingsForm.modifyMode">
            <el-radio label="device">本设备修改</el-radio>
            <el-radio label="batch">批量修改</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 底部操作按钮：取消 / 确认（蓝色） -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="settingsVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSettings">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getFreshAirDeviceList, 
  getFreshAirChartData,
  getFreshAirTransmitterLogs,
  getFreshAirDeviceManage,
  updateFreshAirDeviceManage
} from '@/api/archives/freshair'
import * as echarts from 'echarts'

export default {
  name: 'FreshAirMonitor',
  data() {
    return {
      // 设备数据
      devices: [],
      selectedDevice: null,
      deviceLoading: false,
      
      // 温湿度数据
      temperatureData: '00000',
      humidityData: '00000',
      
      // 阈值展示（默认值，页面联动更新）
      thresholds: {
        tempMin: 14,
        tempMax: 24,
        humMin: 45,
        humMax: 60
      },
      
      // 设备状态
      deviceStatus: {
        power: '关机',
        fanStatus: '未启动',
        fanMode: '自动',
        runMode: '自动'
      },
      
      // 环境数据
      envData: {
        pm25: '00000',
        pm10: '00000',
        co2: '00000',
        tvoc: '00000',
        ch2o: '00000'
      },
      
      // 运行日志
      logs: [],
      logLoading: false,
      
      // 编辑详情弹窗
      settingsVisible: false,
      settingsForm: {
        deviceType: '新风设备',
        warehouse: 'A 库房',
        deviceName: '新风设备_1',
        deviceNumber: '01',
        tempRangeLow: 14,
        tempRangeHigh: 24,
        humRangeLow: 45,
        humRangeHigh: 60,
        tempCoefficient: 0,
        humCoefficient: 0,
        sensorOption: 'self',
        modifyMode: 'device'
      },
      settingsRules: {
        deviceType: [{ required: true, message: '设备类型为必填项', trigger: 'change' }],
        warehouse: [{ required: true, message: '所属库房为必填项', trigger: 'change' }],
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        deviceNumber: [{ required: true, message: '设备编号为必填项', trigger: 'change' }]
      },
      
      // 图表实例
      tempHumChart: null,
      // 图表加载状态，避免重复提交
      chartLoading: false
    }
  },
  
  mounted() {
    this.initData()
    this.initChart()
  },
  
  beforeDestroy() {
    if (this.tempHumChart) {
      this.tempHumChart.dispose()
    }
  },
  
  // 监听设备选择变化，联动阈值与数据
  watch: {
    selectedDevice() {
      this.onDeviceChange()
    }
  },
  
  methods: {
    // 初始化数据
    async initData() {
      await this.getDeviceList()
      // 设备选中后由 onDeviceChange 统一触发日志与曲线刷新
    },
    
    // 刷新数据
    refreshData() {
      this.initData()
      this.$message.success('数据刷新成功')
    },
    
    // 获取设备列表
    async getDeviceList() {
      try {
        this.deviceLoading = true
        const response = await getFreshAirDeviceManage({})
        console.log('设备管理数据响应:', response)
        
        if (response.code === 200) {
          this.devices = Array.isArray(response.data) ? response.data : []
          
          // 更新设备状态统计
          this.updateDeviceStatus()
          
          // 如果有设备，选择第一个设备
          if (this.devices.length > 0) {
            this.selectedDevice = this.devices[0].id
            // 由 selectedDevice 的侦听器触发 onDeviceChange，避免重复调用
          }
        } else {
          this.$message.warning(response.msg || '获取设备列表失败')
          this.devices = []
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
        this.$message.error('获取设备列表失败')
        this.devices = []
      } finally {
        this.deviceLoading = false
      }
    },
    
    // 更新设备状态统计
    updateDeviceStatus() {
      let onlineCount = 0
      let offlineCount = 0
      let alarmCount = 0
      let normalCount = 0
      
      this.devices.forEach(device => {
        // 根据opStatus判断设备状态
        if (device.opStatus === '1') {
          onlineCount++
        } else {
          offlineCount++
        }
        
        // 根据温湿度报警判断设备状态
        if (device.temAlarmUp || device.temAlarmDown || device.humAlarmUp || device.humAlarmDown) {
          alarmCount++
        } else {
          normalCount++
        }
      })
      
      this.deviceStatus = {
        online: onlineCount,
        offline: offlineCount,
        alarm: alarmCount,
        normal: normalCount
      }
    },
    
    // 更新温湿度数据
    updateTempHumData() {
      if (this.devices.length > 0) {
        const currentDevice = this.devices.find(device => device.id === this.selectedDevice)
        if (currentDevice) {
          // 模拟温湿度数据，实际应该从设备实时数据接口获取
          this.temperatureData = Math.floor(Math.random() * 10) + 20 // 20-30度
          this.humidityData = Math.floor(Math.random() * 20) + 40 // 40-60%
        }
      }
    },
    
    // 设备切换时联动阈值展示
    onDeviceChange() {
      const device = this.devices.find(d => d.id === this.selectedDevice)
      if (!device) return
      // 从接口字段映射阈值，注意后端返回为字符串，需转为数字
      this.thresholds = {
        tempMin: device.temAlarmDown !== undefined ? Number(device.temAlarmDown) : 14,
        tempMax: device.temAlarmUp !== undefined ? Number(device.temAlarmUp) : 24,
        humMin: device.humAlarmDown !== undefined ? Number(device.humAlarmDown) : 45,
        humMax: device.humAlarmUp !== undefined ? Number(device.humAlarmUp) : 60
      }
      // 保持其他模块的温湿度数据联动
      this.updateTempHumData()
      // 设备切换时刷新温湿度曲线与运行日志（POST入参联动当前设备）
      this.getChartData()
      this.getLogsList()
    },
    
    // 获取运行日志
    async getLogsList() {
      try {
        // 加载中时直接跳过，避免后端“请勿重复提交”
        if (this.logLoading) return
        this.logLoading = true
        // 构造与设备联动的POST入参（若字段缺失使用合理默认值）
        const device = this.devices.find(d => d.id === this.selectedDevice) || {}
        const logsPayload = {
          storeId: device.storeId || 1,
          deviceTypeCode: device.deviceTypeCode || '01', // 与后端统一入参示例保持一致
          deviceAddrCode: device.deviceAddrCode || '02', // 与示例保持一致，真实场景以设备为准
          termId: device.termId || 1,
          storeCode: device.storeCode || 'A'
        }
        const response = await getFreshAirTransmitterLogs(logsPayload)
        console.log('运行日志响应:', response)
        
        if (response.code === 200 && Array.isArray(response.data)) {
          const logData = response.data
          this.logs = logData.map(log => ({
            id: log.id,
            time: log.createTime,
            content: log.deviceOpLog || '无日志信息',
            deviceName: log.deviceName,
            type: log.logType
          }))
        } else {
          this.logs = []
          if (response.data && !Array.isArray(response.data)) {
            this.$message.warning('日志数据格式不正确')
          }
        }
      } catch (error) {
        console.error('获取运行日志失败:', error)
        this.logs = []
        this.$message.error('获取运行日志失败')
      } finally {
        this.logLoading = false
      }
    },
    
    // 初始化图表
    initChart() {
      this.$nextTick(() => {
        if (this.$refs.tempHumChart) {
          this.tempHumChart = echarts.init(this.$refs.tempHumChart)
          // 初始化仅创建图表实例，数据由设备切换时拉取
        }
      })
    },
    
    // 获取图表数据
    async getChartData() {
      try {
        // 加载中时直接跳过，避免后端“请勿重复提交”
        if (this.chartLoading) return
        this.chartLoading = true
        // 构造与设备联动的POST入参（若字段缺失使用合理默认值）
        const device = this.devices.find(d => d.id === this.selectedDevice) || {}
        const chartPayload = {
          storeId: device.storeId || 1,
          deviceTypeCode: device.deviceTypeCode || '01', // 与后端统一入参示例保持一致
          deviceAddrCode: device.deviceAddrCode || '02', // 与示例保持一致，真实场景以设备为准
          termId: device.termId || 1,
          storeCode: device.storeCode || 'A'
        }
        const response = await getFreshAirChartData(chartPayload)
        console.log('图表数据响应:', response)
        
        if (response.code === 200) {
          const chartData = Array.isArray(response.data) ? response.data : []
          
          // 处理图表数据
          const times = []
          const temperatures = []
          const humidities = []
          
          // 如果没有数据，生成模拟数据用于展示
          if (chartData.length === 0) {
            const now = new Date()
            for (let i = 23; i >= 0; i--) {
              const time = new Date(now.getTime() - i * 60 * 60 * 1000)
              times.push(time.getHours() + ':00')
              temperatures.push(Math.floor(Math.random() * 10) + 20) // 20-30度
              humidities.push(Math.floor(Math.random() * 20) + 40) // 40-60%
            }
          } else {
            // 处理真实数据（兼容后端字段：time/tem/hum）
            chartData.forEach(item => {
              // 优先使用后端提供的小时字段 `time`（如 '09'），否则回退使用 `createTime`
              if (item.time !== undefined && item.time !== null) {
                const label = String(item.time).padStart(2, '0') + ':00'
                times.push(label)
              } else if (item.createTime) {
                const d = new Date(item.createTime)
                times.push(d.getHours() + ':' + String(d.getMinutes()).padStart(2, '0'))
              }
              // 温度与湿度数据字段兼容（tem/hum 或 temperature/humidity），同时做数值化
              const tRaw = item.tem !== undefined ? item.tem : item.temperature
              const hRaw = item.hum !== undefined ? item.hum : item.humidity
              const tVal = typeof tRaw === 'number' ? tRaw : (tRaw !== undefined ? Number(tRaw) : undefined)
              const hVal = typeof hRaw === 'number' ? hRaw : (hRaw !== undefined ? Number(hRaw) : undefined)
              if (tVal !== undefined) temperatures.push(tVal)
              if (hVal !== undefined) humidities.push(hVal)
            })
          }
          
          this.updateChartData(times, temperatures, humidities)
          // 成功后重置加载状态
          this.chartLoading = false
        } else {
          console.warn('获取图表数据失败:', response.msg)
          // 使用模拟数据
          this.generateMockChartData()
        }
      } catch (error) {
        console.error('获取图表数据失败:', error)
        // 使用模拟数据
        this.generateMockChartData()
        // 异常后重置加载状态
        this.chartLoading = false
      }
    },
    
    // 生成模拟图表数据
    generateMockChartData() {
      const times = []
      const temperatures = []
      const humidities = []
      
      const now = new Date()
      for (let i = 6; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 60 * 60 * 1000)
        times.push(time.getHours() + ':00')
        temperatures.push(Math.floor(Math.random() * 10) + 20) // 20-30度
        humidities.push(Math.floor(Math.random() * 20) + 40) // 40-60%
      }
      
      this.updateChartData(times, temperatures, humidities)
    },
    
    // 更新图表数据
    updateChartData(times, temperatures, humidities) {
      if (!this.tempHumChart) return
      
      // 如果没有传入参数或数组为空，使用默认数据
      if (!times || !temperatures || !humidities || times.length === 0 || temperatures.length === 0 || humidities.length === 0) {
        times = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00']
        temperatures = [22, 23, 24, 25, 26, 25, 24]
        humidities = [45, 46, 47, 48, 49, 48, 47]
      }
      
      const option = {
        title: {
          text: '温湿度趋势',
          left: 'center',
          textStyle: {
            fontSize: 14,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['温度(°C)', '湿度(%)'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: [
          {
            type: 'value',
            name: '温度(°C)',
            position: 'left',
            axisLabel: {
              formatter: '{value}°C'
            }
          },
          {
            type: 'value',
            name: '湿度(%)',
            position: 'right',
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series: [
          {
            name: '温度(°C)',
            type: 'line',
            yAxisIndex: 0,
            data: temperatures,
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            },
            lineStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '湿度(%)',
            type: 'line',
            yAxisIndex: 1,
            data: humidities,
            smooth: true,
            itemStyle: {
              color: '#F56C6C'
            },
            lineStyle: {
              color: '#F56C6C'
            }
          }
        ]
      }
      
      this.tempHumChart.setOption(option)
    },
    
    // 显示“编辑详情”弹窗并填充当前设备
    showSettings() {
      this.fillSettingsFromSelected()
      this.settingsVisible = true
    },

    // 根据当前选中设备填写编辑详情
    fillSettingsFromSelected() {
      const device = this.devices.find(d => d.id === this.selectedDevice)
      if (!device) return
      this.settingsForm = {
        deviceType: '新风设备',
        // 库房：使用后端返回 storeName（例如“A库房”），无则回退到 A 库房
        warehouse: device.storeName || (device.storeCode ? `${device.storeCode} 库房` : 'A 库房'),
        // 设备名称：优先 deviceName，其次 alias
        deviceName: device.deviceName || device.alias || '新风设备_1',
        // 设备编号：使用 deviceAddrCode（示例“01”）
        deviceNumber: device.deviceAddrCode || '01',
        // 温度阈值：使用 temAlarmDown / temAlarmUp（字符串需转数字）
        tempRangeLow: device.temAlarmDown !== undefined ? Number(device.temAlarmDown) : this.thresholds.tempMin,
        tempRangeHigh: device.temAlarmUp !== undefined ? Number(device.temAlarmUp) : this.thresholds.tempMax,
        // 湿度阈值：使用 humAlarmDown / humAlarmUp（字符串需转数字）
        humRangeLow: device.humAlarmDown !== undefined ? Number(device.humAlarmDown) : this.thresholds.humMin,
        humRangeHigh: device.humAlarmUp !== undefined ? Number(device.humAlarmUp) : this.thresholds.humMax,
        // 温湿度系数：使用 temAdjust / humAdjust（字符串需转数字）
        tempCoefficient: device.temAdjust !== undefined ? Number(device.temAdjust) : 0,
        humCoefficient: device.humAdjust !== undefined ? Number(device.humAdjust) : 0,
        // 关联传感器：refSensorNo 为 '0000' 时视为自身传感器，否则外置
        sensorOption: device.refSensorNo === '0000' ? 'self' : 'external',
        modifyMode: 'device'
      }
    },

    // 确认编辑详情：校验后调用后端保存，并更新页面阈值与设备数据
    confirmSettings() {
      if (!this.$refs.settingsFormRef) return
      this.$refs.settingsFormRef.validate(async valid => {
        if (!valid) return

        const device = this.devices.find(d => d.id === this.selectedDevice) || {}
        const payload = {
          deviceTypeCode: device.deviceTypeCode || '0B',
          storeId: device.storeId || 1,
          deviceName: this.settingsForm.deviceName,
          deviceAddrCode: this.settingsForm.deviceNumber,
          temAlarmDown: String(this.settingsForm.tempRangeLow),
          temAlarmUp: String(this.settingsForm.tempRangeHigh),
          humAlarmDown: String(this.settingsForm.humRangeLow),
          humAlarmUp: String(this.settingsForm.humRangeHigh),
          temAdjust: String(this.settingsForm.tempCoefficient),
          humAdjust: String(this.settingsForm.humCoefficient),
          refSensorNo: this.settingsForm.sensorOption === 'self' ? '0000' : (device.refSensorNo || '0001'),
          modStatus: this.settingsForm.modifyMode === 'batch' ? 1 : 0,
          termId: device.termId || 1,
          deviceType: '新风设备'
        }

        try {
          const res = await updateFreshAirDeviceManage(this.selectedDevice, payload)
          if (res && res.code === 200) {
            // 更新页面阈值展示
            this.thresholds = {
              tempMin: Number(this.settingsForm.tempRangeLow),
              tempMax: Number(this.settingsForm.tempRangeHigh),
              humMin: Number(this.settingsForm.humRangeLow),
              humMax: Number(this.settingsForm.humRangeHigh)
            }
            // 同步更新设备列表中的当前设备数据
            const idx = this.devices.findIndex(d => d.id === this.selectedDevice)
            if (idx !== -1) {
              this.$set(this.devices, idx, {
                ...device,
                deviceName: payload.deviceName,
                deviceAddrCode: payload.deviceAddrCode,
                temAlarmDown: payload.temAlarmDown,
                temAlarmUp: payload.temAlarmUp,
                humAlarmDown: payload.humAlarmDown,
                humAlarmUp: payload.humAlarmUp,
                temAdjust: payload.temAdjust,
                humAdjust: payload.humAdjust,
                refSensorNo: payload.refSensorNo
              })
            }
            this.$message.success('编辑详情保存成功')
            this.settingsVisible = false
          } else {
            this.$message.error((res && res.msg) || '保存失败')
          }
        } catch (e) {
          console.error('保存编辑详情失败:', e)
          this.$message.error('保存失败，请稍后重试')
        }
      })
    },

    // 设备标签格式化（区域控制器 - 设备名）
    formatDeviceLabel(device) {
      // 后端已返回 alias：例如“区域控制器-新风设备_1”，优先使用以避免重复前缀
      if (device.alias) {
        return device.alias.replace('区域控制器-', '区域控制器 - ')
      }
      const name = device.deviceName || '新风设备_1'
      return `区域控制器 - ${name}`
    }
  }
}
</script>

<style lang="scss" scoped>
.freshair-monitor {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .main-content {
    .device-module,
    .status-module,
    .chart-module,
    .log-module {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;
      
      .module-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
        background: #fafafa;
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 10px;
          
          .title-decorator {
            width: 4px;
            height: 16px;
            background: linear-gradient(135deg, #409eff, #67c23a);
            border-radius: 2px;
          }
          
          .module-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
          
          .device-status {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            
            &.offline {
              background: #fef0f0;
              color: #f56c6c;
            }
            
            &.online {
              background: #f0f9ff;
              color: #67c23a;
            }
          }
        }
      }
    }
    
    // 新风设备模块
    .device-module {
      .device-content {
        padding: 20px;
        
        .device-selector {
          margin-bottom: 20px;
        }
        
        /* 新风设备控制模块：阈值卡片样式 */
        .threshold-cards {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
          margin-top: 4px;

          .threshold-card {
            display: flex;
            align-items: center;
            gap: 12px;
            background: #ecf5ff;
            border: 1px solid #d9ecff;
            border-radius: 8px;
            padding: 12px 14px;

            &.temperature .value { color: #409EFF; }
            &.humidity .value { color: #67C23A; }

            .card-icon {
              width: 28px;
              height: 28px;
              display: flex;
              align-items: center;
              justify-content: center;
            }

            .card-values {
              display: flex;
              flex-direction: column;
              .value {
                font-size: 18px;
                font-weight: 600;
                .unit { margin-left: 4px; font-size: 14px; color: #606266; }
              }
              .desc {
                font-size: 12px;
                color: #909399;
                margin-top: 2px;
              }
            }
          }
        }
        
        /* 区间输入样式：紧凑单行布局，横向排列且不换行 */
        .range-inputs {
          display: inline-flex;
          align-items: center;
          flex-wrap: nowrap; /* 显式不换行，保证单行紧凑 */
          white-space: nowrap; /* 保证在同一行展示 */
          gap: 6px; /* 适度缩小间距，视觉更紧凑 */
          .range-sep { color: #606266; margin: 0 4px; }
          .range-unit { color: #606266; margin-left: 4px; }
          .el-input { width: 100px; } /* 控制输入框宽度，避免换行 */
        }
      }
    }
    
    // 设备状态模块
    .status-module {
      .status-content {
        padding: 20px;
        
        .status-cards {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 15px;
          margin-bottom: 20px;
          
          .status-card {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 6px;
            text-align: center;
            
            .status-label {
              font-size: 12px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .status-value {
              font-size: 14px;
              font-weight: 500;
              color: #303133;
            }
          }
        }
        
        .env-cards {
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          gap: 10px;
          
          .env-card {
            padding: 12px;
            background: #f8f9fa;
            border-radius: 6px;
            text-align: center;
            
            .env-label {
              font-size: 12px;
              color: #909399;
              margin-bottom: 6px;
            }
            
            .env-value {
              .value {
                display: block;
                font-size: 16px;
                font-weight: 600;
                color: #303133;
                margin-bottom: 2px;
              }
              
              .unit {
                font-size: 10px;
                color: #909399;
              }
            }
          }
        }
      }
    }
    
    // 图表模块
    .chart-module {
      .chart-content {
        padding: 20px;
        
        .chart-container {
          width: 100%;
          height: 450px;
        }
      }
    }
    
    // 日志模块
    .log-module {
      .log-content {
        padding: 20px;
        
        .log-table {
          .table-header {
            display: flex;
            background: #f5f7fa;
            border-radius: 4px;
            padding: 12px 0;
            margin-bottom: 10px;
            
            .header-cell {
              flex: 1;
              text-align: center;
              font-size: 14px;
              font-weight: 600;
              color: #606266;
              
              &:first-child {
                flex: 0 0 60px;
              }
              
              &:nth-child(2) {
                flex: 0 0 120px;
              }
            }
          }
          
          .table-body {
            max-height: 200px;
            overflow-y: auto;
            
            .no-data {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 40px 20px;
              
              .no-data-icon {
                margin-bottom: 10px;
                opacity: 0.6;
              }
              
              .no-data-text {
                font-size: 14px;
                color: #c0c4cc;
              }
            }
            
            .table-row {
              display: flex;
              padding: 10px 0;
              border-bottom: 1px solid #ebeef5;
              
              &:last-child {
                border-bottom: none;
              }
              
              .table-cell {
                flex: 1;
                text-align: center;
                font-size: 13px;
                color: #606266;
                
                &:first-child {
                  flex: 0 0 60px;
                }
                
                &:nth-child(2) {
                  flex: 0 0 120px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>